package pl.edu.pw.polygen.util;

import java.util.Locale;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import pl.edu.pw.polygen.MainWindow;
import pl.edu.pw.polygen.PolygenApplication;
import pl.edu.pw.polygen.security.User;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.ui.Window.Notification;

public class ApplicationHelper {

	public static ApplicationContext getApplicationContext() {
		return getApplicationContext(getCurrentApplication());
	}

	private static ApplicationContext getApplicationContext(Application app) {
		if (app == null) {
			return null;
		}
		ServletContext sc = ((WebApplicationContext) app.getContext()).getHttpSession().getServletContext();
		return WebApplicationContextUtils.getWebApplicationContext(sc);
	}
	
	public static User getLoggedUser() {
		Application application = getCurrentApplication();
		if (application == null) {
			return null;
		}
		return (User) application.getUser();
	}

	public static Application getCurrentApplication() {
		return ApplicationHolder.getApplication();
	}

	public static Locale getCurrentLocale() {
		Application application = getCurrentApplication();
		if (application == null) {
			return null;
		}
		return application.getLocale();
	}

	public static String getMessage(String key) {
		return getMessage(key, key);
	}

	public static String getMessage(String key, String defaultMessage) {
		ApplicationSupport applicationSupport = getApplicationSupport();
		if (applicationSupport != null) {
			return getApplicationSupport().getMessage(key);
		} else {
			return defaultMessage;
		}
	}
	

	private static ApplicationSupport getApplicationSupport() {
		ApplicationContext applicationContext = getApplicationContext();
		if (applicationContext == null) {
			return null;
		}
		String names[] = applicationContext.getBeanNamesForType(ApplicationSupport.class);
		if (names != null && names.length == 1) {
			return (ApplicationSupport) getApplicationContext().getBean(names[0]);
		}
		return null;
	}
	
	public static void showNotification(String caption, String description){
		getCurrentApplication().getMainWindow().showNotification(caption, description, Notification.TYPE_TRAY_NOTIFICATION);
	}
	public static void showError(String caption, String description){
		getCurrentApplication().getMainWindow().showNotification(caption, description, Notification.TYPE_ERROR_MESSAGE);
	}
	

}
